﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using DNT.RavenQA.Core.Extensions;
using DNT.RavenQA.Core.Models;
using Raven.Client;

namespace DNT.RavenQA.Web.Infrastructure.Filters
{
    public class FirstRunCheckAttribute : ActionFilterAttribute
    {
        public IDocumentSession Session { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var user = Session.Query<User>().FirstOrDefault();

            if (user.IsNotNull())
                return;

            RedirectIfNotLogInRequest(filterContext);

            base.OnActionExecuting(filterContext);
        }

        private static void RedirectIfNotLogInRequest(ActionExecutingContext actionContext)
        {
            var controllerName = actionContext.RouteData.Values["controller"] as String;
            var actionName = actionContext.RouteData.Values["action"] as String;
            var login = String.Equals("user", controllerName, StringComparison.OrdinalIgnoreCase) &&
                        String.Equals("login", actionName, StringComparison.OrdinalIgnoreCase);

            if (login)
                return;

            actionContext.Result = new RedirectToRouteResult(new RouteValueDictionary
                                               {
                                                   {"action", "LogIn"}, 
                                                   {"controller", "User"}
                                               });
        }
    }
}